package com.sqx.modules.health.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.config.TencentCosConfig;
import com.sqx.modules.health.config.TencentCosProperties4Picture;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 患者康复方案记录表 前端控制器
 * </p>
 *
 * @author hsx
 * @since 2022-09-13
 */
@Slf4j
@Api(value = "上传图片到腾讯云", tags = "", description = "")
@RestController
@RequestMapping("/health/app/huang")
public class AppUploadController {

    /*@Value("${tengxun.SecretId}")
    private String secretId;

    @Value("${tengxun.SecretKey}")
    private String secretKey;

    @Value("${tengxun.region}")
    private String region;

    @Value("${tengxun.bucketName}")
    private String bucketName;

    @Value("${tengxun.url}")
    private String path;*/

    @Autowired
    private TencentCosProperties4Picture tencentCosProperties4Picture;

    @Autowired
    private TencentCosConfig tencentCosConfig;

    @Autowired
    @Qualifier(TencentCosConfig.COS_IMAGE)
    private COSClient cosClient4Picture;


    @PostMapping("/uploadImg")
    @ApiOperation(value = "app更新信息", notes = "app更新信息")
    public Result update(@RequestParam("file") MultipartFile multipartFile) {

        File localFile = null;

        try {
            String originalFilename = multipartFile.getOriginalFilename();
            //logger.info("fileName = {}",originalFilename);
            String[] filename = originalFilename.split("\\.");
            localFile=File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(localFile);

            // 图片压缩
            Thumbnails.of(localFile)
                    //图片大小（长宽）压缩比例 从0-1，1表示原图
                    .scale(1f)
                    //图片质量压缩比例 从0-1，越接近 1 质量越好
                    .outputQuality(0.1f)
                    .toFile(localFile);
            localFile.deleteOnExit();
        } catch (IOException e) {
            //logger.info("MultipartFile transto file IOException ={}",e.getMessage());
            //throw new HuihuaException(ResultCode.SYSTEM_ERROR.getCode(),ResultCode.SYSTEM_ERROR.getMsg());
        }

        if(localFile == null){
            //throw new HuihuaException(ResultCode.MULTIPART_FILE_EOORO.getCode(),ResultCode.MULTIPART_FILE_EOORO.getMsg());
        }

        String key = TencentCosConfig.COS_IMAGE + "/" + System.currentTimeMillis() + ".png";
        //logger.info("key = {}", key);

        PutObjectRequest putObjectRequest =
                new PutObjectRequest(tencentCosProperties4Picture.getBucketName(), key, localFile);
        //设置存储类型 默认标准型
        putObjectRequest.setStorageClass(StorageClass.Standard);

        COSClient cosClient = tencentCosConfig.getCoSClient4Picture();

        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //putObjectResult 会返回etag
            String etag = putObjectResult.getETag();
            //logger.info("eTag = {}", etag);
        } catch (CosServiceException e) {
            //logger.error("CosServiceException ={}", e.getMessage());
            throw new CosServiceException(e.getMessage());
        } catch (CosClientException e) {
            //logger.error("CosClientException ={}", e.getMessage());
            throw new CosClientException(e.getMessage());
        }
        cosClient.shutdown();
        String url = tencentCosProperties4Picture.getBaseUrl()+ "/" + key;
        Map<String, Object> res = new HashMap<>();
        res.put("url", url);
        return Result.success(res);
    }

    /*public COSClient initCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }*/

    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String originalfileName) {
        String filePath = "test/";
        //1.获取后缀名 2.去除文件后缀 替换所有特殊字符
        String fileType = originalfileName.substring(originalfileName.lastIndexOf("."));
        String fileStr = StrUtil.removeSuffix(originalfileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
        filePath += new DateTime().toString("yyyyMMddHHmmss") + "_" + fileStr + fileType;
        return filePath;
    }

}

